package com.csun.cmny.provider.controller;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.config.RedisInitRunner;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.dto.ShowAllLeaveDto;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcBillItem;
import com.csun.cmny.provider.model.domain.OmcOldManAccountFunds;
import com.csun.cmny.provider.model.domain.OmcOldManBill;
import com.csun.cmny.provider.model.vo.old_out.AccountFundsOfLeyiVo;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.pojo.OldmanCheckIn;
import com.csun.cmny.provider.pojo.OldmanFee;
import com.csun.cmny.provider.pojo.OldmanLeave;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.vo.OldmanBedInfoVo;
import com.csun.cmny.provider.vo.OldmanLeaveVo;
import com.csun.cmny.provider.vo.SettleDetailVo;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;


/*
 * 老人出院管理
 * */
@RestController
@RequestMapping("/OldmanLeave")
public class OldmanLeaveController extends BaseController {

    @Resource
    private RedisInitRunner redisInitRunner;
    @Autowired
    private OldmanCheckInService oldmanCheckInService;
    @Autowired
    private OldmanLeaveService oldmanLeaveService;
    @Autowired
    private BedService bedService;
    @Autowired
    private CacRpcService cacRpcService;
    @Autowired
    private OldmanService oldmanService;
    @Autowired
    private OldmanFeeService oldmanFeeService;
    @Autowired
    private OldmanRechargeService oldmanRechargeService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;


    /**
     *
     * 查询出院记录
     * @param dto
     * @return
     */
    @RequestMapping(value = "/showLeaveMan", method = RequestMethod.POST)
    public Wrapper<PageInfo<OldmanLeaveVo>> showLeaveMan( @RequestBody ShowAllLeaveDto dto) {

        String pageNo = dto.getPageNo();
        String pageSize = dto.getPageSize();
        dto.setHomeId(getLoginAuthDto().getGroupId());

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<OldmanLeaveVo> oldmanLeaveVoList = oldmanLeaveService.showAll(dto);
        for (OldmanLeaveVo vo:oldmanLeaveVoList) {
            if (vo.getMonetary() == null ){vo.setMonetary(BigDecimal.ZERO);}
            if (vo.getRemainder() == null ){vo.setRemainder(vo.getActPaidFee().subtract(vo.getDeposit()));}
        }
        PageInfo<OldmanLeaveVo> pageInfo = new PageInfo<>(oldmanLeaveVoList);

//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), pageInfo);
    }

    /**
     * 乐怡查询出院记录
     * @param: [dto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @RequestMapping(value = "/queryOldmanLeaveListWithPage", method = RequestMethod.POST)
    public Wrapper queryOldmanLeaveListWithPage(@RequestBody ShowAllLeaveDto dto) {

        String pageNo = dto.getPageNo();
        String pageSize = dto.getPageSize();
        dto.setHomeId(getLoginAuthDto().getGroupId());

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<OldmanLeaveVo> oldmanLeaveVoList = oldmanLeaveService.queryOldmanLeaveListWithPage(dto);
        PageInfo<OldmanLeaveVo> pageInfo = new PageInfo<>(oldmanLeaveVoList);
//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), pageInfo);
    }

    /**
     * 乐怡查询出院记录
     * @param: [dto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @RequestMapping(value = "/listPage", method = RequestMethod.POST)
    public Wrapper listPage(@RequestBody ShowAllLeaveDto dto) {

        String pageNo = dto.getPageNo();
        String pageSize = dto.getPageSize();
        dto.setHomeId(getLoginAuthDto().getGroupId());

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<OldmanLeaveVo> oldmanLeaveVoList = oldmanLeaveService.listPage(dto);
        PageInfo<OldmanLeaveVo> pageInfo = new PageInfo<>(oldmanLeaveVoList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), pageInfo);
    }

    /**
     *
     * 结算弹框回显
     * @param oldmanId
     * @return
     */
    @RequestMapping(value = "/showSettleDetailByOid", method = RequestMethod.POST)
    public Wrapper<SettleDetailVo> showSettleDetailByOid ( Integer oldmanId){
        if (oldmanId == null){
            return WrapMapper.error("老人id不能为空");
        }
        OldmanCheckIn oldmanCheckIn = oldmanCheckInService.selectById(oldmanId);
        //实缴金额
        BigDecimal actPaidFee = oldmanCheckIn.getActPaidFee();
        //押金
        BigDecimal deposit =oldmanCheckIn.getDeposit();
        BigDecimal balance = BigDecimal.ZERO;
        SettleDetailVo settleDetailVo = oldmanLeaveService.getLeaveByOid(oldmanId);
        BigDecimal rechargeTotal = oldmanRechargeService.getRechargeTotal(oldmanId);
        settleDetailVo.setRecharge(rechargeTotal);
        //余额
        BigDecimal remainder = settleDetailVo.getRemainder();
        if (settleDetailVo != null) {
            if (remainder == null ) {
                remainder = actPaidFee.subtract(deposit);
            }

            settleDetailVo.setDeposit(deposit);
            balance = deposit.add(remainder);
            if (settleDetailVo.getActPaidFee() == null){settleDetailVo.setActPaidFee(actPaidFee);}
            if (settleDetailVo.getMonetary() == null){
                settleDetailVo.setMonetary(BigDecimal.ZERO);
            }
            if (settleDetailVo.getRemainder() == null){settleDetailVo.setRemainder(remainder);}
            settleDetailVo.setBalance(balance);
        }
//        return WrapMapper.ok(settleDetailVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), settleDetailVo);
    }

    /**
     * 乐颐费用结算详情
     * @param: [oldmanId]
     * @return: com.csun.cmny.util.wrapper.Wrapper<com.csun.cmny.provider.vo.SettleDetailVo>
     */
    @RequestMapping(value = "/getSettleDetailByOldmanId/{oldmanId}", method = RequestMethod.POST)
    public Wrapper getSettleDetailByOldmanId (@PathVariable Integer oldmanId){
       if (oldmanId == null){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("oldman.id.null", null));
        }
        AccountFundsOfLeyiVo vo = oldmanLeaveService.getSettleDetailByOldmanId(oldmanId);
//        return WrapMapper.ok(vo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), vo);
    }

    /**
     * 乐颐-结算费用出院
     * @param: [oldmanId]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @RequestMapping(value = "/ensureOldmanFee/{oldmanId}", method = RequestMethod.POST)
    public Wrapper ensureOldmanFee (@PathVariable Integer oldmanId){
        if (oldmanId == null){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("oldman.id.null", null));
        }
        int ret = oldmanLeaveService.ensureOldmanFee(oldmanId,getLoginAuthDto());
//        return WrapMapper.ok(ret);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), ret);
    }

    /**
     * 确认结算
     * @param oldmanId
     * @return
     */
    @RequestMapping(value = "/closeAccounts", method = RequestMethod.POST)
    public Wrapper closeAccounts(Integer oldmanId){
        if (oldmanId == null){
//            return  WrapMapper.error("老人Id不能为空");
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("oldman.id.null", null), null);
        }

        // 校验老人是否在院
        Oldman oldmanQuery = new Oldman();
        oldmanQuery.setOldmanId(oldmanId);
        oldmanQuery = oldmanService.selectByOld(oldmanQuery);
        if (!oldmanQuery.getStatus().equals(Constant.YIRUYUAN)) {
//            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"老人不是入院状态",null);
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("oldman.not.in", null),null);
        }

        LoginAuthDto loginAuthDto = getLoginAuthDto();
        OldmanLeave oldmanLeave = new OldmanLeave();
        oldmanLeave.setOldmanId(oldmanId);
        oldmanLeave.setModifier(loginAuthDto.getUserId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            oldmanLeave.setLeaveDate(sdf.parse(DateUtil.getCurrentDate()));
            oldmanLeave.setCreateTime(sdf.parse(DateUtil.getCurrentDate()));
            oldmanLeave.setModifyTime(sdf.parse(DateUtil.getCurrentDate()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        OldmanBedInfoVo oldmanBedInfoVo = bedService.selectByOid(oldmanId);
        int n = oldmanLeaveService.updateByOid(oldmanLeave);
        if (n > 0) {
            int m = bedService.updateByOid(oldmanId);
            if (m < 1) {
                logger.info("出院结算时解绑床位失败");
            }

        }
        // 刷新缓存
        redisInitRunner.refreshOldman(oldmanId);
        if (PublicUtil.isNotEmpty(oldmanBedInfoVo)) {
            redisInitRunner.refreshBed(oldmanBedInfoVo.getBedId());
        }

        //根据老人Id删除评估及小项信息
        Integer k = cacRpcService.deleteByOldmanId(oldmanId);
        if (k<1){logger.info("出院时删除评估记录失败");}
        //出院后清空老人余额 保留消费金额和预缴金额
        OldmanFee oldmanFee = new OldmanFee();
        oldmanFee.setCheckinoldmanId(oldmanId);
        oldmanFee.setRemainder(new BigDecimal(0));
        oldmanFeeService.updateByPrimaryKeySelective(oldmanFee);
        oldmanCheckInService.outByOldmanId(oldmanId);
//        return WrapMapper.ok(n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), n);
    }

    /**
     * 根据id删除出院信息
     * @param leaveId
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    public Wrapper deleteById(Integer leaveId){
        if (leaveId == null){
            WrapMapper.error("出院id不能为空");
        }
        int n = oldmanLeaveService.deleteByPrimaryKey(leaveId);
//        return   n>0 ? WrapMapper.ok(): WrapMapper.error();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), n);
    }
}
